package org.csc.sss.core.repository.base;

import org.csc.sss.core.repository.*;
import org.csc.sss.core.repository.impl.PersonRepositoryImpl;
import org.csc.sss.core.repository.impl.SysUserRepositoryImpl;
import org.csc.sss.core.security.SecurityUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.Map;

public class BaseRepositoryImpl {
    @PersistenceContext
    public EntityManager entityManager;//实体管理对象


    @Autowired
    public SysUserRepository sysUserRepository;
    @Autowired
    public PersonRepository personRepository;
    @Autowired
    public SysUserRoleRepository sysUserRoleRepository;
    @Autowired
    public SysRolePermissionRepository sysRolePermissionRepository;
    @Autowired
    public SysPermissionRepository sysPermissionRepository;


    @Autowired
    public PersonRepositoryImpl personRepositoryImpl;
    @Autowired
    public SysUserRepositoryImpl sysUserRepositoryImpl;


    /**
     * 获取当前登录的用户
     * @return
     */
    protected SecurityUser getUser() {
        if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof SecurityUser) {
            return (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }
        return  null;
    }

    /**
     * 给hql参数设置值
     * @param query 查询
     * @param params 参数
     */
    protected void setParameters(Query query, Map<String,Object> params){
        for(Map.Entry<String,Object> entry:params.entrySet()){
            query.setParameter(entry.getKey(),entry.getValue());
        }
    }

    /**
     * 对象拷贝
     * @param dto 被拷贝的对象
     * @param model
     */
    protected void copyProperties(Object dto, Object model) {
        BeanUtils.copyProperties(dto, model);
    }
}
